package com.epro.dx.activity;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.epro.dx.R;
import com.epro.dx.listenner.OnLoginSuccessedListenner;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.DialogUtils;
import com.epro.dx.util.LoginUtilTask;
import com.epro.dx.widget.BottomBtn;
import com.epro.dx.widget.BottomBtn.OnBtnClickListenner;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.ScreenViewBuilder;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.observer.RedDotObserver;
import com.weipu.common.subject.RedDotSubjectImpl;
import com.weipu.common.util.Logger;
import com.weipu.common.util.ThreadUtil;
import com.weipu.common.util.utils.SPUtils;
import java.lang.ref.WeakReference;

public class HomeActivity extends BaseFragmentActivity{
    public BottomBtn mIndicator;

    public static Fragment[] mFragments;

    private static final String TAG = HomeActivity.class.getSimpleName();

    public static final String CURRENT_TAB_TAG = "current_tab_tag";

    public static final int titleArray[] = {R.string.function_bar_home,
            R.string.function_bar_browse, R.string.function_bar_shopping_cart,
            R.string.function_bar_account};
    /**
     * 购物车总数
     */
    private int shoppingCartTotal;

    public String currentTab;

    private boolean isNewIntent;

    private OnTouchEventListenner touchEventListenner;

    public Tracker tracker;

    private ScreenViewBuilder screenViewBuilder;
    private DialogUtils dialogUtils;

    private Handler handler;
    private SPUtils spUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
//                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
//                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
//                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        tracker = ((DXApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);
        screenViewBuilder = new HitBuilders.ScreenViewBuilder();

        handler = new GlobalHandler(DXApplication.getContext());
        //表示非增量更新 增量更新支持需要引入libbspatch.so文件
        //http://dev.umeng.com/auto-update/android-doc/quick-start
        //友盟更新代码已经无用，注释掉
//		UmengUpdateAgent.setDeltaUpdate(false);
//		UmengUpdateAgent.forceUpdate(this);
//		UmengUpdateAgent.setUpdateCheckConfig(false);

        setContentView(R.layout.home_layout);
        // --------修改：加入购物车同步的线上逻辑-----------
        getAndSetCount();
        setFragmentIndicator(0);
        spUtils = new SPUtils(getResources().getString(R.string.app_name_en));
        //从SP当中取出是否显示过的更新对话框的标记,如果已经显示过，就不再弹出更新对话框了
        boolean isShowUpdateDialog = spUtils.getBoolean(Constant.Global.IS_SHOW_UPDATE_DIALOG, false);
        //检查更新，首先会从服务器获取最新的版本好，然后和自己应用内的版本进行比较，如果服务器大于自己的，就弹窗提醒用户更新
        if (!isShowUpdateDialog) {
            checkUpdate();
        }


    }

    /**
     * 检查更新
     */
    private void checkUpdate() {

        //开启一个线程来获取新版本
        ThreadUtil.getInstance().getThreadPoolIntance().submit(new Runnable() {
            @Override
            public void run() {
                if (ProviderFactory.createUpdateService().checkUpdateCancelable(HomeActivity.this)) {

                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            final View dialogView = LayoutInflater.from(HomeActivity.this).inflate(R.layout.dialog_update, null);
                            dialogUtils = new DialogUtils.Builder(HomeActivity.this)
                                    .setContentView(dialogView)
                                    .setEtContent(spUtils.getString(Constant.Global.APP_UPDATE_CONTENT))
                                    .setViewClick(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            switch (v.getId()) {
                                                case R.id.btn_yes:
                                                    gotoGooglePlay();
                                                    break;

                                                case R.id.btn_remind_no_more:
                                                    //以后都不在显示这个更新对话框,即将显示过的标记放入SharedPreferences当中存储
                                                    spUtils.put(Constant.Global.IS_SHOW_UPDATE_DIALOG, true);
                                                    break;

                                                case R.id.btn_remind_later:

                                                default:
                                                    break;
                                            }
                                            //对话框消失
                                            dialogUtils.dismiss();
                                        }
                                    }, R.id.btn_yes, R.id.btn_remind_later, R.id.btn_remind_no_more)
                                    .build();
                            dialogUtils.showDialog();
                        }
                    });
//
                }
            }
        });


    }

    /**
     * 跳转到谷歌商店，如果设备上有谷歌商店
     */
    private void gotoGooglePlay() {
        //打开谷歌商店，让用户自行下载
        try {
            Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.android.vending");
            if (null == launchIntent) {
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName())));
            } else {
                ComponentName comp =
                        new ComponentName("com.android.vending",
                                "com.google.android.finsky.activities.LaunchUrlHandlerActivity");
                launchIntent.setComponent(comp);
                launchIntent.setData(Uri.parse("market://details?id=" + getPackageName()));
                startActivity(launchIntent);
            }
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName())));
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        currentTab = intent.getStringExtra(HomeActivity.CURRENT_TAB_TAG);
        isNewIntent = true;
        super.onNewIntent(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Logger.d(TAG, "onSaveInstanceState");
        // super.onSaveInstanceState(outState);
    }

    /**
     * 设置提醒数目
     *
     * @param num 新增数目
     * @see [类、类#方法、类#成员]
     */
    public void setShoppingCartToast(int num) {
        shoppingCartTotal += num;
        if (null != mIndicator) {
            mIndicator.setToastNum(shoppingCartTotal);
        }
    }

    /**
     * 设置tab显示
     *
     * @param tag
     * @see [类、类#方法、类#成员]
     */
    public void setCurrentTabByTag(String tag) {
        mIndicator.setCurrentTab(tag);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 解决 java.lang.IllegalStateException: Can not perform this action after
        // onSaveInstanceState
        // 即不能在"onSaveInstanceState"之后改变fragment问题
        // 参考http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html
        /*
         * if (TextUtils.isEmpty(currentTab)) {
		 * setCurrentTabByTag(getString(titleArray[0])); } else
		 */
//		if (!TextUtils.isEmpty(currentTab)) {
        if (isNewIntent && !TextUtils.isEmpty(currentTab)) {
            isNewIntent = false;
            if (BottomBtn.ACCOUNT_TAG.equals(currentTab)) {
                mIndicator.accountShow();
            } else {
                setCurrentTabByTag(currentTab);
            }

            Logger.i(TAG, "currentTAB: " + currentTab);
        }
        //GA页面跟踪
        tracker.setScreenName(mIndicator.getCurrentTab());
        tracker.send(screenViewBuilder.build());
        //
        // if (GlobalConfig.getInstance().isShoppingCartChange()) {
        // shoppingCartTotal = ProviderFactory.createMyCartServiceDBProvider()
        // .getCartTotal(this);
        // setShoppingCartToast(0);
        getAndSetCount();
        // }
    }

    /**
     * 初始化fragment
     */
    private void setFragmentIndicator(final int whichIsDefault) {

        mFragments = new Fragment[4];
        FragmentManager fragmentManager = getSupportFragmentManager();
        mFragments[0] = fragmentManager.findFragmentById(R.id.fragment_home);
        mFragments[1] = fragmentManager.findFragmentById(R.id.fragment_browse);
        mFragments[2] = fragmentManager
                .findFragmentById(R.id.fragment_shoppingCart);
        mFragments[3] = fragmentManager
                .findFragmentById(R.id.fragment_settings);
        fragmentManager.beginTransaction().hide(mFragments[0])
                .hide(mFragments[1]).hide(mFragments[2]).hide(mFragments[3])
                .show(mFragments[whichIsDefault]).commitAllowingStateLoss();

        mIndicator = (BottomBtn) findViewById(R.id.bottomBtn);
        mIndicator.setViewStatus(0);
        mIndicator.setBtnClickListenner(new OnBtnClickListenner() {

            @Override
            public void setCurrentFragment(int which) {
//				if (which == 3) {
//					if (!ActivityUtil.isLogin(getApplicationContext())) {
//						gotoLogin();
//						return;
//					}
//				}
                getSupportFragmentManager().beginTransaction()
                        .hide(mFragments[0]).hide(mFragments[1])
                        .hide(mFragments[2]).hide(mFragments[3])
                        .show(mFragments[which]).commitAllowingStateLoss();
                //GA页面跟踪
                tracker.setScreenName(mIndicator.getCurrentTab());
                tracker.send(screenViewBuilder.build());
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Logger.d(TAG, "CurrentTabTag:" + mIndicator.getCurrentTab());
            if (!TextUtils.equals(getString(titleArray[0]),
                    mIndicator.getCurrentTab())) {
                setCurrentTabByTag(getString(titleArray[0]));
                return true;
            }

            AlertDialog exitDialog = new AlertDialog.Builder(this)
                    .setTitle(R.string.exit)
                    .setMessage(R.string.confirm_exit)
                    .setPositiveButton(R.string.btn_yes,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    exit();
                                }
                            })
                    .setNegativeButton(R.string.btn_no,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();

                                }
                            }).create();
            exitDialog.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (TextUtils.equals(getString(titleArray[0]),
                mIndicator.getCurrentTab())) {
            Logger.i(TAG, "HomeActivity is touch");
            touchEventListenner.onTouch(ev);
        }
        try {
            return super.dispatchTouchEvent(ev);
        } catch (IllegalArgumentException ignored) {
        } catch (ArrayIndexOutOfBoundsException e) {
        }
        return false;
    }

    public interface OnTouchEventListenner {
        void onTouch(MotionEvent event);
    }

    public void setTouchEventListenner(OnTouchEventListenner listenner) {
        this.touchEventListenner = listenner;
    }

    /**
     * 跳转登录界面
     *
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void gotoLogin() {
        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
        Bundle data = new Bundle();
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                ServerConstant.Parameter.PARAMETER_ACTION_TYPE_MYACCOUNT);
        intent.putExtras(data);
        startActivity(intent);
    }

    /**
     * @author tony 查询线上购物车中产品品类数量
     */
    class QueryCount extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                shoppingCartTotal = ProviderFactory
                        .createShoppingCartServiceProvider().getCartCount(
                                Long.parseLong(getCustomerID()), ActivityUtil.getCustomerToken());
            } catch (DxException e) {
                return e.getErrCode();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            if (null != result) {
                if ("DMS100002".equals(result)) {
                    LoginUtilTask logintask = new LoginUtilTask(
                            new OnLoginSuccessedListenner() {

                                @Override
                                public void onLoginSuccesed() {
                                    AsyncTaskUtil.executeTask(new QueryCount());
                                }

                                @Override
                                public void onLoginFailed() {

                                }
                            }, HomeActivity.this, false);
                    AsyncTaskUtil.executeTask(logintask);
                }
            }
            setShoppingCartToast(0);
            super.onPostExecute(result);
        }
    }

    /**
     * 获取购物车商品品类数并显示到小红点
     */
    public void getAndSetCount() {
        if (!ActivityUtil.isLogin(getApplicationContext())) {
            // 没有登陆执行本地逻辑
            shoppingCartTotal = ProviderFactory.createMyCartServiceDBProvider()
                    .getCartTotal(this);
            setShoppingCartToast(0);

        } else {
//			String isUpload = StringUtil.getConfig("IsUploadSucc", "true");
//			Logger.i(TAG, "isUpload "+isUpload);
//			if ("true".equals(isUpload)) {
            // 已经登陆，执行线上逻辑
            AsyncTaskUtil.executeTask(new QueryCount());
//			} else {
//				// 还没有同步执行本地逻辑
//				shoppingCartTotal = ProviderFactory
//						.createMyCartServiceDBProvider().getCartTotal(this);
//				setShoppingCartToast(0);
//			}

        }
    }

    public static class GlobalHandler extends Handler {
        private WeakReference<Context> weakReference;

        public GlobalHandler(Context context) {
            weakReference = new WeakReference<Context>(context);
        }


    }
}
